package com.shd.edanpei.presenter;


import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.model.NoDataResponse;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.TeamModel;
import com.shd.edanpei.presenter.contract.MyTeamContract;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by mc on 2018/11/20.
 * yang-wen-wen
 */

public class MyTeamPresenter extends BasePresenterImpl<MyTeamContract.MyTeamIView>
        implements MyTeamContract.MyTeamIPresenter {

    public MyTeamPresenter(MyTeamContract.MyTeamIView mView) {
        super(mView);
    }

    @Override
    public void queryTeamInfo() {
        mBaseIView.showLoading("");
        ApiCreator.getApi().queryMyTeam()
                .compose(RxTransformer.<TeamModel>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<TeamModel>() {
                    @Override
                    protected void onSuccess(TeamModel data) {
                        //已加入团队
                        mBaseIView.setTeamData(data);
                    }


                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
    }

    @Override
    public void uploadPicture(final String picPath, final int teamID) {
        ApiCreator.getApi().uploadPicture(createFileBody(picPath), createStrBody("1"))
                .compose(RxTransformer.<String>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    protected void onSuccess(String data) {
                        uploadTeamLogo(data, teamID);

                    }
                });
    }

    private void uploadTeamLogo(final String picPath, final int teamID) {
        ApiCreator.getApi().updateTeamLogo(picPath, teamID)
                .compose(RxTransformer.<NoDataResponse>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NoDataResponse>() {
                    @Override
                    protected void onSuccess(NoDataResponse data) {

                    }
                });
    }

    private MultipartBody.Part createFileBody(final String pic) {
        File file = new File(pic);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
        return MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    }

    private RequestBody createStrBody(final String value) {
        return RequestBody.create(MediaType.parse("text/plain"), value);
    }

}
